﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace App_Code.Helpers
{
    /// <summary>
    /// Summary description for MytubeExtractor
    /// </summary>
    public class MytubeExtractor
    {
        private const string CONTROL_URI = "http://www.mytube.co.il/media/nuevo/config.php?key={0}";
        private const string PLAYLIST_TEMPLATE = "http://www.mytube.co.il/media/nuevo/playlist.php?key={0}";
        private const string URL_REGEX = "www.mytube.co.il.*?key=([A-Za-z0-9]+)";
        private const string MOVIE_URL = "www.mytube.co.il?key={0}";

        public static List<string> GetMovieUrls(string content)
        {
            var movieUrls = new List<string>();
            var exp = new Regex(URL_REGEX, RegexOptions.IgnoreCase);
            var matches = exp.Matches(content);
            foreach (Match match in matches)
            {
                if (match.Success)
                {
                    var movieUrl = string.Format(MOVIE_URL, match.Groups[1].Value);
                    if (!movieUrls.Contains(movieUrl))
                    {
                        movieUrls.Add(movieUrl);
                    }
                }
            }
            return movieUrls;
        }

        public static VideoResult ExtractMovieUrl(string movieUrl)
        {
            var movieCode = movieUrl.Substring(movieUrl.Length - 8);
            var playListUrl = string.Format(PLAYLIST_TEMPLATE, movieCode);
            var reader = new XmlTextReader(playListUrl);
            // Skip non-significant whitespace  
            reader.WhitespaceHandling = WhitespaceHandling.Significant;
            // Read nodes one at a time  
            while (reader.Read())
            {
                // Print out info on node  
                Console.WriteLine("{0}: {1}", reader.NodeType.ToString(), reader.Name);
            } 

            var content = Utils.GetPage(playListUrl, Encoding.Default);

            var MovieLinkMatch = Regex.Match(content, "<file>(.+?)</file>", RegexOptions.IgnoreCase);
            if (!MovieLinkMatch.Success)
            {
                throw new Exception("Cant find movie link");
            }

            var MovieNameMatch = Regex.Match(content, "<title>(.+?)</title>", RegexOptions.IgnoreCase);

            return new VideoResult(MovieLinkMatch.Groups[1].Value, MovieNameMatch.Groups[1].Value, true);
        }

        public static bool IsContainVideoLink(string content)
        {
            var match = Regex.Match(content, "mytube", RegexOptions.IgnoreCase);
            return match.Success;
        }
    }
}